#  $Id: forms.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
#  Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
#  
#  Permission to use, copy, modify, and distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
# 
#  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

import string
import datetime

from django import forms
from django.contrib.auth.models import User
from django.forms import util, ValidationError

from djanet.db import choices, netdb, ssndb, query
from djanet.lib import exception, stdlib, ip
from djanet.tools.lib import tree, whois, ipv6, util
from djanet.utils import utils

class LoginForm(forms.Form):
   djanet_username = forms.CharField(max_length = 15, label = 'Username',
         help_text = 'AD/Email username')
   djanet_password = forms.CharField(max_length = 25, label = 'Password',
         help_text = 'AD/Email password', widget = forms.PasswordInput)
   djanet_remember = forms.BooleanField(required = False,
         label = 'Remember me')

class WhoisForm(forms.Form):
   asnumber = forms.IntegerField(max_value = 65535, min_value = 0,
         help_text = "BGP AS number", label = 'ASN', required = False)
   ipaddress = forms.IPAddressField(help_text = 'IP address',
         label = 'IP Address ', required = False)
   whoisserver = forms.ChoiceField(choices = choices.WHOIS_SERVERS,
         required = True, label = "Server", initial = "None",
         help_text = "Whois Servers")
   whoisinfo = forms.CharField(help_text = 'Whois information',
         label = 'Whois info ', widget = forms.Textarea, required = False)

   def __init__(self, *args, **kwargs):
      self._log = utils.loghandle(stdlib.my_name(self))
      self._defServer = "whois.arin.net"
      self._version = 4
      super(stdlib.my_class(self), self).__init__(*args, **kwargs)

   def whois_asn(self, ASNumber, Server):
      retval = None
      if ASNumber and len(tree.ASNList):
         entry = None
         for node in tree.ASNList:
            if ASNumber in node:
               entry = node
               break

         client = None
         try:
            if Server:
               client = whois.Whois(Server)
            else:
               if entry:
                  client = whois.Whois(entry[ASNumber])
               else:
                  client = whois.Whois(self._defServer)
         except exception.WhoisError, message:
            raise forms.ValidationError, message
         else:
            query = None
            if Server:
               query = "as%s\r\n" %(str(ASNumber))
            else:
               if entry:
                  query = "%s%s\r\n" %(entry.query, str(ASNumber))
               else:
                  query = "as%s\r\n" %str(ASNumber)

            if query:
               retval = client.info(query)
         finally:
            if client:
               client.Close()

         return retval

   def whois_ipv4(self, Address, Server):
      retval = None
      if Address and len(tree.IPv4List):
         address = None
         try:
            address = ip.ip(Address)
         except exception.IPError, message:
            raise forms.ValidationError, message
         else:
            if address.size() > 1:
               address = address[0]

         entry = None
         for node in tree.IPv4List:
            if address in node:
               entry = node
               break

         client = None
         try:
            if Server:
               client = whois.Whois(Server)
            else:
               if entry:
                  client = whois.Whois(entry[address])
               else:
                  client = whois.Whois(self._defServer)
         except exception.WhoisError, message:
            raise forms.ValidationError, message
         else:
            query = None
            query = "%s\r\n" %str(address)
            """
            if entry:
               query = "%s%s\r\n" %(entry.query, str(address))
            else:
               query = "%s\r\n" %str(address)
            """

            retval = client.info(query)
         finally:
            if client:
               client.Close()

      return retval

   def GetInfo(self, kwargs = {}):
      retval = None
      asn = None
      ip = None
      server = None

      if "asnumber" in kwargs:
         try:
            if kwargs['asnumber']:
               asn = int(kwargs['asnumber'])
         except ValueError, message:
            raise forms.ValidationError(message)

      if "ipaddress" in kwargs:
         ip = kwargs['ipaddress']

      if "server" in kwargs:
         server = kwargs["server"].lower()
         if server == "none":
            server = None

      try:
         if asn:
            retval = self.whois_asn(asn, server)
         elif ip:
            retval = self.whois_ipv4(ip, server)
      except forms.ValidationError, message:
         raise forms.ValidationError(message)

      return retval

   def clean(self):
      ipaddress = self.cleaned_data.get('ipaddress')
      if ipaddress:
         temp = None
         try:
            temp = ip.ip(ipaddress)
         except exception.IPError, message:
            self._log.info(message)
            raise forms.ValidationError(message)

         if temp.version != self._version:
            self._log.info(message)
            raise forms.ValidationError('Invalid IP address version')

         self.cleaned_data['ipaddress'] = temp

      return self.cleaned_data
